<?php

namespace app\web\service;

use app\common\logic\OrderLogic;
use app\common\model\commonModel;
use app\common\model\trCar;
use app\common\model\trDriver;
use app\common\model\trOrder;
use app\common\model\trOrderOutletsDetail;
use app\common\model\trOutletsCar;
use app\common\model\trResource;
use app\common\model\trUser;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use app\common\util\WxPay;
use think\Db;

/**
 * Class Auth
 * @package app\web\service
 * 订单服务类
 */
class OrderService
{
    private $returnData;
    private $params;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
    }

    public function getList(){
        if (empty($this->params["type"])) { //；1机场接送，2巴士线路，3跨境专车接送，4包车线路
            return ErrorCode::code("params_not_exist", "type");
        }
        if(!in_array($this->params["type"], [1,2,3,4,5])){
            return ErrorCode::code("params_error", "type");
        }
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        $model = new trOrder();
        $data = $model->getList("*", ["type" => $this->params["type"], "user_id" => request()->userLoginData["id"]], $page, $pageSize);
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    public function getDetail(){
        if (empty($this->params["orderSn"])) {
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        $model = new trOrder();
        $data = $model->getFields("*", ["order_sn" => $this->params["orderSn"], "user_id" => request()->userLoginData["id"]]);
        if($data) {
            if(($i = strrpos($data["addressFrom"], " ")) !== false) {
                $data["addressFromDetail"] = substr($data["addressFrom"], $i + 1);
                $data["addressFrom"] = substr($data["addressFrom"], 0, $i);
            }
            if(($i = strrpos($data["addressTo"], " ")) !== false) {
                $data["addressToDetail"] = substr($data["addressTo"], $i + 1);
                $data["addressTo"] = substr($data["addressTo"], 0, $i);
            }
            if(!empty($data["longLatFrom"])) {
                list($data["longitudeFrom"], $data["latitudeFrom"]) = explode(",", $data["longLatFrom"]);
            }
            if(!empty($data["longLatTo"])) {
                list($data["longitudeTo"], $data["latitudeTo"]) = explode(",", $data["longLatTo"]);
            }
            $url = $data["orderSn"];
            // 司机已接单
            if($data["status"] == "7"){
                $driverModel = new trDriver();
                if(empty($driverData = $driverModel->getFields("mobile,nickname", ["id" => $data["allotDriverId"]], true, false))){
                    $driverData["mobile"] = "";
                    $driverData["nickname"] = "";
                }
                $carModel = new trCar();
                if(empty($carData = $carModel->getFields("plate_number,model_number,appearance", ["id" => $data["allotCarId"]], true, false))){
                    $carData["plateNumber"] = '';
                    $carData["appearance"] = '';
                    $carData["modelNumber"] = '';
                }
                $data["driverData"] = [
                    "plateNumber" => $carData["plateNumber"], "appearance" => $carData["appearance"], "modelNumber" => $carData["modelNumber"], "mobile" => $driverData["mobile"], "driverName" => $driverData["nickname"]
                ];
            }
            if($data['type'] == '5'){
                $data["reserveTime"] = str_replace(" ", " 至 ", $data["reserveTime"]);
                $detail = trOrderOutletsDetail::where("order_id", $data["id"])->find();
                $data["outletsServer"] = $detail->serve ? @json_decode($detail->serve, true) : [];
                $temp = trOutletsCar::alias("oc")->leftJoin(trCar::getTable()." c", "c.id=oc.car_id")
                    ->where(["oc.id" => $detail->oc_id])
                    ->field("c.model_number,c.appearance,c.icon,c.name,c.type")
                    ->find();
                $data["outletsData"] = [
                    "appearance" => $temp->appearance, "modelNumber" => $temp->model_number, "plateNumber" => $detail->plate_number,
                    "carIcon" => tome_dia(trResource::getValue("url", ["id" => $temp->icon])), "carName" => $temp->name,
                    "carType" => $temp->type == 1 ? "燃油" : ($temp->type == 2 ? "电动" : "混动")
                ];
                $url = json_encode(["orderSn" => $data["orderSn"], "type" => 5]);
            }
            // 核销码
            $data["writeOffQrCode"] = '';
            if($data["status"] == '2'){
                $data["writeOffQrCode"] = request()->domain()."/web/qrCode?url=".urlencode($url);
            }
        }
        $this->returnData["data"] = $data;
        return $this->returnData;
    }

    // 申请退款
    public function toApplyRefund(){
        if (empty($this->params["orderSn"])) {
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        $orderModel = new trOrder();
        //  `status` tinyint(3) DEFAULT 1 COMMENT '订单状态：1待支付，2已支付，3已取消；4待分配；5已分配；6司机拒接；7司机已接单；8已完成；9已退款；10待退款；11部分退款',
        // 线路，订单在预定时间内可以退款，超过不行
        $orderData = $orderModel->getFields("user_id,type,status,trade_no,reserve_time", Db::raw("`order_sn` = '{$this->params["orderSn"]}'"), true, false);
        if(empty($orderData)){
            return ErrorCode::code("customized", "订单不存在");
        }
        if($orderData["reserveTime"] <= date("Y-m-d H:i:s")){
            return ErrorCode::code("customized", "订单的发车时间已过");
        }
        if(empty($orderData["tradeNo"])){
            return ErrorCode::code("customized", "订单未付款");
        }
        if($orderData["status"] == "9"){
            return ErrorCode::code("customized", "订单已经退款了");
        }
        if($orderData["status"] == "8"){
            return ErrorCode::code("customized", "订单已经结束了");
        }
        if($orderData["status"] == "10"){
            return ErrorCode::code("customized", "订单已经在申请退款");
        }
        try {
            $res = commonModel::toAdd(refundTable, [
                "user_id" => $orderData["userId"],
                "order_sn" => $this->params["orderSn"],
                "type" => $orderData["type"],
                "money" => 0,
                "status" => 1,
                "ip" => Tools::get_client_ip(),
                "create_time" => time(),
            ]);
            if($res){
                $orderModel->doUpdate(["status" => 10], ["order_sn" => $this->params["orderSn"]]);
            }else{
                $this->returnData = ErrorCode::$errorCode["fail"];
                $this->returnData["msg"] = "系统异常，无法申请退款";
            }
        }catch (\Exception $e){
            $this->returnData = ErrorCode::$errorCode["fail"];
            $this->returnData["msg"] = "已经申请退款了";
        }
        return $this->returnData;
    }

    // 取消
    public function toCancel(){
        if (empty($this->params["orderSn"])) {
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        $model = new trOrder();
        $orderData = $model->getFields("status", ["order_sn" => $this->params["orderSn"], "user_id" => request()->userLoginData["id"]], true, false);
        if(empty($orderData)){
            $this->returnData["msg"] = "订单不存在";
            return $this->returnData;
        }
        if($orderData["status"] == "3"){ //取消订单
            $this->returnData["msg"] = "订单已取消";
            return $this->returnData;
        }
        if($orderData["status"] == "8"){ // 完成订单
            $this->returnData["msg"] = "订单已完成";
            return $this->returnData;
        }
        $orderLogic = new OrderLogic();
        $res = $orderLogic->cancelOrder($this->params["orderSn"], request()->userLoginData["id"], isset($this->params["reason"]) ? $this->params["reason"] : "");
        if(isset($res["code"])){
            return $res;
        }
        if(!$res) {
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "订单取消失败";
        }
        return $this->returnData;
    }

    // 重新支付
    public function toPay(){
        if (empty($this->params["orderSn"])) {
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        $model = new trOrder();
        $orderData = $model->getFields("type,line_id,pay_money", ["order_sn" => $this->params["orderSn"], "user_id" => request()->userLoginData["id"]]);//固定路线支付
        if(empty($orderData)){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "订单不存在";
            return $this->returnData;
        }
        $paymentNo = $model->getPayNo();
        $userModel = new trUser();
        $openid = $userModel->getValue("openid", ["id" => request()->userLoginData["id"]]);
        $res = $model->doUpdate(["payment_no" => $paymentNo], ["order_sn" => $this->params["orderSn"]]);
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "更新订单失败";
            return $this->returnData;
        }
        $data = ["total_fee" => $orderData["payMoney"] * 100, "openid" => $openid, "out_trade_no" => $paymentNo, "body" => "支付"];
        // 加的测试
        if(in_array(request()->host(), ["cardemo.wegouer.com/test/cars-pai", "service-emhatyrq-1251017581.gz.apigw.tencentcs.com/test/cars-pai"])) {
            $data["total_fee"] = 1; // 测试 1毛
        }
        $wxPay = new WxPay();
        $res = $wxPay->toPay($data); // 获取支付信息
        if(isset($res["code"])){
            $this->returnData = $res;
        }else{
            $res["orderSn"] = $this->params["orderSn"];
            $this->returnData["data"] = $res;
        }
        return $this->returnData;
    }

    // 判断订单是否支付了
    public function getJudge(){
        if (empty($this->params["orderSn"])) {
            return ErrorCode::code("params_not_exist", "orderSn");
        }
        $model = new trOrder();
        $status = $model->getValue("status", ["order_sn" => $this->params["orderSn"]]);
        if($status == "1"){
            $this->returnData["data"] = ["isPay" => 0];
        }else{
            $this->returnData["data"] = ["isPay" => 1];
        }
        return $this->returnData;
    }
}